/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: DynamicSqlFunction.java   2020-10-10 21-19-18
 * Author: Evan
 */
package cn.datacare.orm.engine.function;

import cn.datacare.orm.manager.impl.SQLManager;
import cn.datacare.orm.source.SQLResult;
import cn.datacare.orm.source.SQLSource;
import org.beetl.core.Context;
import org.beetl.core.Function;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.datacare.orm.constant.Constants.PARAM_MANAGER;
import static cn.datacare.orm.constant.Constants.PARAM_PARAMS;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-10 21-19-18
 * @since V1.0
 */
public class DynamicSqlFunction implements Function {


    private static final int PARAMS_SIZE = 2;

    @Override
    public Object call(Object[] paras, Context ctx) {
        String sqlTemplate = (String) paras[0];
        String key = "auto._gen_" + sqlTemplate;

        Map inputParas = ctx.globalVar;
        if (paras.length == PARAMS_SIZE) {
            Map map = (Map) paras[1];
            map.putAll(inputParas);
            inputParas = map;
        }

        SQLManager sm = (SQLManager) ctx.getGlobal(PARAM_MANAGER);
        // 保留参数和映射关系，免得被覆盖
        List list = (List) ctx.getGlobal(PARAM_PARAMS);

        SQLSource source = sm.getSqlLoader().getSQL(key);
        if (source == null) {
            source = new SQLSource(key, sqlTemplate);
            sm.getSqlLoader().addSQL(key, source);
        }

        SQLResult result = sm.getSQLResult(source, inputParas);
        //追加参数
        list.addAll(result.getJdbcParam());
        ctx.set(PARAM_PARAMS, list);
        try {
            ctx.byteWriter.writeString(result.getJdbcSql());
        } catch (IOException e) {

        }
        return null;
    }
}
